package cn.springcloud.consumer.controller;


import cn.springcloud.api.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author gc
 * @Date 2019/12/10 14:35  周二
 * @Description
 */


/**
 *  @FeignClient 参考  https://blog.csdn.net/u010889990/article/details/78673273
 */

@RestController
@RequestMapping("/user")
@Slf4j
@FeignClient
public class UserController {
    @Autowired
    @LoadBalanced
    private RestTemplate restTemplate ;

    @Autowired
    private LoadBalancerClient loadBalancerClient;



    @RequestMapping("/getUser")
    @ResponseBody
    public List<User> getUser(){
        //List list = restTemplate.getForObject("http://localhost:8080/user/getUser", List.class);
        // 消费服务  springCloudProvider  --->               对应服务的 ip:port
        return restTemplate.getForObject("http://springCloudProvider/user/getUser", List.class);
    }
    @RequestMapping("/{id}")
    @ResponseBody
    public User getUser(@PathVariable String id){
        User user =  restTemplate.getForObject("http://localhost:8080/user/"+id, User.class);
        //User user =  restTemplate.getForObject("http://springCloudProvider/user/"+id, User.class);
        return user;
    }



    /**
     * 当前 服务者 实例
     */
    @RequestMapping(value = "/instance")
    public String logUserInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("springCloudProvider");
        System.out.println("serviceId:"+serviceInstance.getServiceId()+"  host:"+serviceInstance.getHost()+"  port:"+serviceInstance.getPort());
        log.info("这是实例选择---》"+serviceInstance.getServiceId()+"——"+serviceInstance.getHost()+"——"+serviceInstance.getPort());
        return "serviceId:"+serviceInstance.getServiceId()+" --》 host:"+serviceInstance.getHost()+" --》 port:"+serviceInstance.getPort();
    }






}
